import {
  CarpoolMemberCreat,
  CarpoolMemberUpdate,
} from '../interface/params.interface.ts'
import {
  toSnakeCase,
  backResult,
  selectResultsHandle,
} from '../utils/common.ts'
import CarpoolMember from '../model/carpoolmember.model.ts'
import CarpoolType from '../model/carpooltype.model.ts'

class CarpoolMemberService {
  async selectAllCarpoolMember() {
    const res: any = await CarpoolMember.findAll({
      include: [
        {
          model: CarpoolType,
          as: 'carpoolTypeInfo',
          attributes: ['carpool_type_name'],
        },
      ],
    })
    return selectResultsHandle(res)
  }

  // 查询拼车成员
  async selectCarpoolMember(carpoolMemberIds: string[]) {
    const res: any = await CarpoolMember.findAll({
      where: {
        carpool_member_id: {
          $or: carpoolMemberIds,
        },
      },
    })
    return selectResultsHandle(res)
  }

  // 创建拼车成员
  async inseretCarpoolMember(obj: CarpoolMemberCreat) {
    const option = toSnakeCase(obj)
    const res: any = await CarpoolMember.create(option)
    return res ? res.dataValues : null
  }

  // 更新拼车成员
  async updateCarpoolMember(obj: CarpoolMemberUpdate) {
    const { carpool_member_id, ...option } = toSnakeCase(obj)
    const res: any = await CarpoolMember.update(option, {
      where: { carpool_member_id },
    })
    return backResult(res)
  }

  // 删除拼车成员
  async deleteCarpoolMember(obj: { carpoolMemberId: string }) {
    const { carpool_member_id } = toSnakeCase(obj)
    const res: number = await CarpoolMember.destroy({
      where: { carpool_member_id },
    })
    return backResult(res)
  }
}

const carpoolMemberService = new CarpoolMemberService()
export const {
  selectCarpoolMember,
  inseretCarpoolMember,
  updateCarpoolMember,
  deleteCarpoolMember,
  selectAllCarpoolMember,
} = carpoolMemberService
export default carpoolMemberService
